package 链表;

/**
 * 203. 移除链表元素 (https://leetcode-cn.com/problems/remove-linked-list-elements/)
 * 给你一个链表的头节点 head 和一个整数 val ，请你删除链表中所有满足 Node.val == val 的节点，并返回 新的头节点
 * User: zhaixiaolong Date:2024/1/3 10:37 ProjectName: algorithm Version: V1
 */
public class 移除链表元素 {

    /**
     * 初始化链表
     *
     * @return
     */
    public static Node initData() {
        Node node1 = new Node();
        node1.value = 1;
        Node node2 = new Node();
        node2.value = 4;
        Node node3 = new Node();
        node3.value = 3;
        Node node4 = new Node();
        node4.value = 2;
        Node node5 = new Node();
        node5.value = 5;
        Node node6 = new Node();
        node6.value = 2;


        node1.next = node2;
        node2.next = node3;
        node3.next = node4;
        node4.next = node5;
        node5.next = node6;

        return node1;
    }

    /**
     * 开辟一个新链表
     *
     * @param head
     * @param v
     * @return
     */
    public static Node removeNode(Node head, int v) {
        Node newHead = new Node();
        Node headTemp = newHead;
        while (head != null) {
            if (head.value != v) {
                newHead.next = head;
                newHead = newHead.next;
            }
            head = head.next;
        }
        newHead.next = null;
        return headTemp.next;
    }

    /**
     * 双指针
     *
     * @param head
     * @param v
     * @return
     */
    public static Node removeNode2(Node head, int v) {


        Node newHead = new Node();
        Node pre = newHead;
        Node cur = head;
        while (cur != null) {
            if (cur.value == v) {
                pre.next = cur.next;
            } else {
                pre = cur;
            }
            cur = cur.next;
        }
        return newHead.next;
    }

    public static void main(String[] args) {
        Node head = initData();
        int v = 2;
        Node newH = removeNode2(head, v);
        System.out.println(newH);
    }


}
